<template>
  <div class="hello">
    <div>===================这里是组件2 start==================</div>
    组件1状态机==={{ key1 }}
    <button @click="handleAdd">更新key2</button>
    <div>===================这里是组件2 end==================</div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      key1: 0,
    };
  },
  watch: {
    "$Store.store": {
      deep: true,
      handler(val) {
        console.log("======", val);
      },
    },
  },
  computed: {
    store({ $Store }) {
      return $Store.store;
    },
  },
  created() {
    this.key1 = this.$Store.store.key1;
  },
  mounted() {
    this.$Store.subscribe("key1", (newValue) => {
      this.key1 = newValue;
      console.log(`这里是组件2,key1新值=`, newValue);
    });
    this.key1 = this.$Store.store.key1;
  },
  methods: {
    handleAdd() {
      const arr = this.$Store.store.key2;
      const key3 = this.$Store.store.key3;
      // key3.c += 1;
      if (key3.d) {
        // key3.d += 1;
      } else {
        // key3.d = 1;
      }
      if (key3?.e?.a) {
        key3.e.a += 1;
      } else {
        key3.e = {};
        key3.e.a = 1;
      }
      arr.push(Date.now());
      this.$Store.dispatch("key2", arr);
      this.$Store.dispatch("key3", key3);
      console.log("===========组件2 handleAdd");
      // store.key2.a += 1;
      // if (store.key2.b) {
      //   store.key2.b += 1;
      // }
      // if (!store.key2.c) {
      //   store.key2.c = {
      //     ca1: 0,
      //   };
      //   store.key2.c.ca1 += 1;
      // } else {
      //   console.log("store", store.key2);
      //   store.key2.c.ca1 += 1;
      // }
      // console.log("store", store.key2);
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
